package beusoft.ccjk.com.calculator.sort;

import javax.xml.transform.Templates;

/**
 * Created by CCJK on 2017/12/24.
 */

public class ShellSort {


    private static void println(Object o) {
        System.out.println(o);
    }

    private static void print(Object o) {
        System.out.print(" " + o);
    }

    private static void printArr(int arr[]) {
        print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                print(arr[i]);
            } else {
                print(arr[i] + " , ");
            }

        }
        print("]");
    }

    public static void main(String... args) {

    }

    /**
     * 希尔排序
     * 增量公式：h=3h+1
     *
     * @param arr
     */
    public static void sort(int arr[]) {
        int h = getMaxH(arr);
        int outer, inner, temp;

        while (h > 0) {
            for (outer = h; outer < arr.length; outer++) {
                inner = outer;
                temp = arr[outer];
                while (inner > (h - 1) && arr[inner - h] >= temp) {
                    arr[inner] = arr[inner - h];
                    inner -= h;

                }
                arr[inner] = temp;
            }
            h = (h - 1) / 3;
        }

    }

    private static int getMaxH(int[] arr) {
        int h = 0;
        while (h <= (arr.length / 3)) {
            h = 3 * h + 1;
        }
        return h;
    }

}
